package com.woniuxy.xiangruicommonutilserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.bean.ResultBean;
import com.woniuxy.xiangruicommonutilserver.service.IMinioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author: masterhai
 * @date: 2021/4/5:13:11
 * @description:
 */
@RefreshScope
@Slf4j
@Api(tags = "minio文件存储相关接口")
@RequestMapping("/minio")
@RestController
public class MinioController {
    @Value("${my.minio.bucket_name}")
    private String defaultBucketName;
    @Resource
    private IMinioService minioService;

    @PostMapping("upload/{bucketName}")
    @ApiOperation(value = "上传文件")
    public ResultBean saveFile (@ApiParam("桶名") @PathVariable(value = "bucketName",required = false) String bucketName,
                            @ApiParam("上传文件") @RequestParam("file") MultipartFile file) {
        if (file == null) {
            return ResultBean.ParamError();
        }
        return minioService.saveFile(StringUtils.isEmpty(bucketName) ? defaultBucketName : bucketName, file);
    }

    //删除文件
    @PostMapping("delete/{bucketName}")
    @ApiOperation(value = "删除指定文件")
    public ResultBean removeFile (@ApiParam("桶名") @PathVariable(value = "bucketName",required = false) String bucketName,
                              @ApiParam("文件全路径名") @RequestParam("objectName") String objectName) {
        if (StringUtils.isEmpty(objectName)) {
            return ResultBean.ParamError();
        }
        minioService.removeFile(StringUtils.isEmpty(bucketName) ? defaultBucketName : bucketName, objectName);
        return ResultBean.builder().code(200).msg("文件删除成功").build();
    }

    //查询桶中所有文件
    @GetMapping("select/{bucketName}")
    @ApiOperation(value = "查询指定桶中所有文件")
    public ResultBean listFileByBucket (@ApiParam("桶名") @PathVariable("bucketName") String bucketName) {
        if (StringUtils.isEmpty(bucketName)) {
            return ResultBean.ParamError();
        }
        return minioService.listFileByBucket(bucketName);
    }
}
